import { useRef, useState } from 'react'

type Props = {
  onAddTodo: (text: string) => void
}

const TodoAdd = ({ onAddTodo }: Props) => {
  // 输入框输入的最新值
  let [value, setValue] = useState('')

  const inputRef = useRef<HTMLInputElement>(null)

  // 监听状态的改变
  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value)
  }

  // 监听回车事件
  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    const inputDom = inputRef.current!

    if (inputDom.value.trim() === '') return

    if (e.code === 'Enter') {
      // 将任务名称传递给父组件
      onAddTodo(inputDom.value)

      // 添加任务后，清空文本框的值
      setValue('')
    }
  }

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        ref={inputRef}
        value={value}
        onChange={onChange}
        onKeyDown={onKeyDown}
        className="new-todo"
        placeholder="What needs to be done?"
        autoFocus
      />
    </header>
  )
}

export default TodoAdd
